#include "stdafx.h"
#include "CtpLinkBase.h"
#include "config.h"


CtpLinkBase::CtpLinkBase() {
	memset(mBrokerID, ' ', mFieldSize);
	memset(mUserID, ' ', mFieldSize);
	memset(mPassword, ' ', mFieldSize);
	memset(mInvestor, ' ', mFieldSize);
	memset(mTradingDay, ' ', mFieldSize);
}

void CtpLinkBase::loadSettings() {
	Config *cfg = Config::getInstance();
	string brokerID, user, password, instruments, instrument, investor;
	brokerID = cfg->getValue("BrokerID." + mName, "0000");
	user = cfg->getValue("User." + mName, "1234");
	password = cfg->getValue("Password." + mName, "9999");
	instruments = cfg->getValue("Instruments", "");
	investor = cfg->getValue("Investor", "1234");
	mAllInstruments = instruments;
	int pos = instruments.find(",");
	int len;
	while(pos != string::npos) {
		mInstrumentsVector.push_back(instruments.substr(0, pos));
		len = instruments.length() - pos - 1;
		if( len <= 0 ) break;
		instruments = instruments.substr(pos+1, len);
		pos = instruments.find(",");
	}
	if(instruments.length() > 0) mInstrumentsVector.push_back(instruments);

	mInstrumentsArray = new char *[mInstrumentsVector.size()];
	
	for(size_t i=0; i<mInstrumentsVector.size(); i++) {
		mInstrumentsArray[i] = new char [32];
		sprintf(mInstrumentsArray[i], "%s", mInstrumentsVector[i].c_str());
	}

	sprintf_s(mBrokerID, mFieldSize, "%s", brokerID.c_str());
	sprintf_s(mUserID, mFieldSize, "%s", user.c_str());
	sprintf_s(mPassword, mFieldSize, "%s", password.c_str());
	sprintf_s(mInvestor, mFieldSize, "%s", investor.c_str());
}


CtpLinkBase::~CtpLinkBase(void) {
}

bool CtpLinkBase::setLoginField(CThostFtdcReqUserLoginField *login) {
	strncpy_s(login->BrokerID, sizeof(TThostFtdcBrokerIDType), mBrokerID, strlen(mBrokerID));
	strncpy_s(login->UserID, sizeof(TThostFtdcUserIDType), mUserID, strlen(mUserID));
	strncpy_s(login->Password, sizeof(TThostFtdcPasswordType), mPassword, strlen(mPassword));

	return true;
}

bool CtpLinkBase::RspError(CThostFtdcRspInfoField *info, const string &name, stringstream &ss) {
	if( info && info->ErrorID != 0 ) {
		ss << "Error in " << name << ". ErrorCode=" << info->ErrorID << ". ErrorMsg=" << info->ErrorMsg;
		return true;
	} else {
		return false;
	}
}

string CtpLinkBase::getSide(TThostFtdcDirectionType side) {
	switch ( side ) {
	case THOST_FTDC_D_Buy: return "Buy";
	case THOST_FTDC_D_Sell: return "Sell";
	default: return "Wrong side";
	}
}